<?php

defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.model');

class ScorecardModelScore extends JModel {
	var $_countries = null;
	var $_states = null;
	var $_courses = null;

	var $_countryid = null;
	var $_stateid = null;
	var $_courseid = null;
	var $_fromdate = null;
	var $_todate = null;
	var $_status = null;

	var $_usergender = null;

	function __construct() {
		parent::__construct();

		$countryid = JRequest::getVar('countryid', null, '', 'int');
		$this->_countryid = $countryid;

		$stateid = JRequest::getVar('stateid', null, '', 'int');
		$this->_stateid = $stateid;

		$courseid = JRequest::getVar('courseid', null, '', 'int');
		$this->_courseid = $courseid;

		$fromdate = JRequest::getVar('fromdate', '', '', 'string');
		$this->_fromdate = $fromdate;

		$todate = JRequest::getVar('todate', '', '', 'string');
		$this->_todate = $todate;

		$status = JRequest::getVar('status', 1, '', 'int');
		$this->_status = $status;

		$this->getUserGender();
	}

	function getCountryId() {
		return $this->_countryid;
	}

	function getStateId() {
		return $this->_stateid;
	}

	function getCourseId() {
		return $this->_courseid;
	}

	function getFromDate() {
		return $this->_fromdate;
	}

	function getToDate() {
		return $this->_todate;
	}

	function getStatus() {
		return $this->_status;
	}

	function getUserGender() {
		$user =& JFactory::getUser();
		$query = "SELECT gender FROM #__user_extra_info WHERE userid = '" . $user->id . "'";
		$this->_db->setQuery($query);
		$this->_usergender = $this->_db->loadResult();
	}

	function setCountryId($id) {
		$this->_countryid = $id;
	}

	function setStateId($id) {
		$this->_stateid = $id;
	}

	function setCourseId($id) {
		$this->_courseid = $id;
	}

	function getCountries() {
		if (!$this->_countries) {
			$query = "SELECT * FROM #__countries ORDER BY name ASC";
			$this->_countries = $this->_getList($query, 0, 0);
			// Select first country by default
			if (!isset($this->_countryid) && count($this->_countries) > 0) {
				$this->_countryid = $this->_countries[0]->id;
			}
		}
		return $this->_countries;
	}

	function getStates($countryid = null) {
		if (!$this->_states) {
			if ($this->_countryid) {
				$query = "SELECT * FROM #__states WHERE countryid = '" . ($countryid !== null ? $countryid : $this->_countryid) . "' ORDER BY name ASC";
				$this->_states = $this->_getList($query, 0, 0);
				// Select first state by default
				if (!isset($this->_stateid) && count($this->_states) > 0) {
					$this->_stateid = $this->_states[0]->id;
				}
			}
		}
		return $this->_states;
	}

	function getCourses($countryid = null, $stateid = null) {
		if (!$this->_courses) {
			$query = "SELECT * FROM #__golfcourses WHERE stateid = '" . ($stateid !== null ? $stateid : $this->_stateid) . "' AND countryid ='" . ($countryid !== null ? $countryid : $this->_countryid) . "' ORDER BY name ASC";
			$this->_courses = $this->_getList($query, 0, 0);
		}
		return $this->_courses;
	}

	function getAdjustedScore(&$row) {
		$query = "SELECT score FROM #__score_holes WHERE scoreid = '" . $row['id'] . "'";
		$this->_db->setQuery($query);
		$raws = $this->_db->loadRowList();

		$query = "SELECT " . ($this->_usergender == 1 ? 'parwomen' : 'parmen') . " FROM #__golfcard_holes WHERE scorecardid = '" . $row['scorecardid'] . "'";
		$this->_db->setQuery($query);
		$pars = $this->_db->loadRowList();

		// Adjust raw score
		for ($j = 0, $c = count($raws); $j < $c; $j++) {
			$raws[$j] = min($raws[$j], $pars[$j] + 2);
		}
		$gross_score = array_sum($raws);
		return $gross_score;
	}

	function getBuffZone($handicap_int) {
		// Get buffer zone
		if ($handicap_int <=4) {
			$buff_zone = 0;
		} else if ($handicap_int >=5 && $handicap_int <=12) {
			$buff_zone = 1;
		} else if ($handicap_int >=13 && $handicap_int <= 19) {
			$buff_zone = 2;
		} else if ($handicap_int >= 20 && $handicap_int <=27) {
			$buff_zone = 3;
		} else {
			$buff_zone = 3;
		}
		return $buff_zone;
	}

	function getHandicap() {
		$user =& JFactory::getUser();

		$query = " SELECT S.id, SC.id as scorecardid, S.playdate, SC.acr, SC.awcr as score FROM #__golfcourses C, #__golferscores S, #__score_holes H, #__scorecard_holes SH, #__scorecards SC" .
				 " WHERE C.id = S.courseid" .
				 " AND H.scoreid = S.id" .
				 " AND C.scorecardid = SC.id" .
				 " AND SC.id = SH.scorecardid" .
				 " AND S.userid = '" . $user->id . "'" .
				 " GROUP BY S.id" .
				 " ORDER BY S.playdate ASC ";
		$this->_db->setQuery($query);
		$cards = $this->_db->loadAssocList();
		$count = count($cards);
		// Not enough cards to calculate handicap
		if ($count < 5) {
			return 9999;
		}
		// Select 5 earliest scorecards to calculate initial handicap
		for ($i = 0; $i < 5; $i++) {
			$row =& $cards[$i];
			$gross_score = $this->getAdjustedScore($row);
			$handicap_diff += $gross_score - ($this->_usergender == 1 ? $row['awcr'] : $row['acr']);
		}
		$initial_handicap = round($handicap_diff/5, 1);
		$handicap = $initial_handicap;

		for ($i = 5; $i < $count; $i++) {
			$row =& $cards[$i];
			$gross_score = $this->getAdjustedScore($row);
			$handicap_diff = $gross_score - ($this->_usergender == 1 ? $row['awcr'] : $row['acr']);

			$buff_zone = $this->getBuffZone(round($handicap));

			if ($handicap_diff > $handicap + $buff_zone) {
				$handicap += 0.1;

				// Special case in category A
				if ($buff_zone == 0 && ($handicap_diff > $handicap + 5)) {
					$handicap += 0.1;
				}
			} else if ($handicap_diff < $handicap) {
				// Complicated cases
				$strokes = round($handicap) - $handicap_diff;
				if ($strokes >=1) {
					$handicap = $this->getDecsHandicap($handicap, $strokes);
				}
			}
		}
		return round($handicap, 1);
	}

	function getDecsHandicap($handicap, $strokes) {
		$buff_zone = $this->getBuffZone(round($handicap));
		$ret = $handicap;

		if ($buff_zone == 0) {
			$dec = 0.1;
		} else if ($buff_zone == 1) {
			$dec = 0.2;
		} else if ($buff_zone == 3) {
			$dec = $handicap > 27 ? 0.5 : 0.4;
		}
		while (1) {
			$ret -= $dec;
			$strokes --;
			if ($strokes <=0) break;
			// Check if handicap is reduced to the right below category
			if ($this->getBuffZone($ret) != $buff_zone) {
				$ret = $this->getDecsHandicap($ret, $strokes);
			}
		}
		return $ret;
	}

	function searchScores($limitstart = 0, $limit = 0) {
		global $mainframe;

		$user =& JFactory::getUser();

		jimport('joomla.utilities.date');


		$where = " AND S.userid = '" . $user->id . "'";
		if ($this->_fromdate) {
			$date = new JDate($this->_fromdate);
			$where .= " AND S.playdate >='" . $date->toMySQL() . "'";
		}
		if ($this->_todate) {
			$date = new JDate($this->_todate);
			$where .= " AND S.playdate <='" . $date->toMySQL() . "'";
		}
		if ($this->_countryid) {
			$where .= " AND C.countryid = '" . $this->_countryid . "'";
		}
		if ($this->_stateid) {
			$where .= " AND C.stateid = '" . $this->_stateid . "'";
		}
		if ($this->_courseid) {
			$where .= " AND C.id = '" . $this->_courseid . "'";
		}

		$where = ltrim($where, ' AND ');

		// Get count of records
		$query = " SELECT COUNT(DISTINCT S.id) as total FROM #__golfcourses C, #__golferscores S, #__score_holes H, #__scorecard_holes SH, #__scorecards SC" .
				 " WHERE C.id = S.courseid" .
				 " AND H.scoreid = S.id" .
				 " AND C.scorecardid = SC.id" .
				 " AND SC.id = SH.scorecardid" .
				 " AND ". $where;
		$this->_db->setQuery($query);
		$total = $this->_db->loadResult();

		// Get actual records
		$query = " SELECT DISTINCT S.id as scoreid, C.id as courseid, SC.id as scorecardid, S.playdate, C.name FROM #__golfcourses C, #__golferscores S, #__score_holes H, #__scorecard_holes SH, #__scorecards SC" .
				 " WHERE C.id = S.courseid" .
				 " AND H.scoreid = S.id" .
				 " AND C.scorecardid = SC.id" .
				 " AND SC.id = SH.scorecardid" .
				 " AND ". $where .
				 " GROUP BY S.id" .
				 " ORDER BY S.playdate DESC, C.name ASC";
		$this->_db->setQuery($query, $limitstart, $limit);
		$rows = $this->_db->loadAssocList();
		$itemid = JRequest::getVar('Itemid');

		if (count($rows) > 0) {
			for ($i = 0, $c = count($rows); $i < $c; $i++) {
				$row =& $rows[$i];
				$row['name'] = '<a href="index.php?option=com_scorecard&view=course&Itemid=' . $itemid . '&courseid=' . $row['courseid'] . '">' . $row['name'] . '</a>';

				$date = new JDate($row['playdate']);
				$row['playdate'] = $date->toFormat('%d-%m-%Y');
				$scorecardid =& $row['scorecardid'];
				$par = ($this->_usergender == 1) ? 'SUM(parwomen)' : 'SUM(parmen)';
				$query = "SELECT " . $par . " FROM #__scorecard_holes WHERE scorecardid = '" . $scorecardid . "'";
				$this->_db->setQuery($query);
				$row['par'] = $this->_db->loadResult();

				$query = "SELECT SUM(score) FROM #__score_holes WHERE scoreid = '" . $row['scoreid'] . "'";
				$this->_db->setQuery($query);
				$row['score'] = $this->_db->loadResult();
				$row['score'] = '<a href="index.php?option=com_scorecard&view=scorecard&Itemid=' . $itemid . '&scoreid=' . $row['scoreid'] . '">' . $row['score'] . '</a>';
			}
		}

		$handicap = $this->getHandicap();

		return array('total' => $total, 'rows' => $rows, 'handicap' => $handicap);
	}
}
?>